﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameView.Comment;
using GameView.Models;
using GameView.Services.Comment;
using GameView.Services.Dtos.Persons;
using MaterialDesignThemes.Wpf;
using System.Collections.ObjectModel;

namespace GameView.ViewModels
{
    public partial class AssignProjectViewModel : ObservableObject
    {
        private readonly ProjectService _service;
        private readonly UserService _userService;

        public AssignProjectViewModel(ProjectService service, UserService userService)
        {
            _userService = userService;
            _service = service;
            LoadData().ConfigureAwait(false);
        }

        public void SetPersonInfo(PersonnelOutDto personnel)
        {
            UserId = personnel.Id;
            UserName = personnel.Account;
            UserRole = personnel.RoleName;
            roleId = personnel.RoleId.Value;
        }

        public void SetPersonInfo(PersonnelOutDto personnel, List<ProjectPersonRelationEntity> pp)
        {
            UserId = personnel.Id;
            UserName = personnel.Account;
            UserRole = personnel.RoleName;
            roleId = personnel.RoleId.Value;
            pps = pp;
        }

        private int roleId = 0;

        [ObservableProperty]
        private bool _isLoading = false;

        [ObservableProperty]
        private bool? _selectAll = false;

        [ObservableProperty]
        private ObservableCollection<TreeNode> _nodes = new();

        [ObservableProperty]
        private string _userName = string.Empty;

        [ObservableProperty]
        private string _userRole = string.Empty;

        [ObservableProperty]
        private int _userId = 0;

        [ObservableProperty]
        [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
        private TreeNode? _selectedNode;

        private List<ProjectPersonRelationEntity> pps = [];
        private List<ProjectPersonRelationEntity> OldPPS = null;

        [RelayCommand]
        private void SelectedItemChanged(object selectedItem)
        {
            // 设置新选中的项
            if (selectedItem is TreeNode newNode)
            {
                //newNode.IsSelected = true;
                SelectedNode = newNode;
            }
            else
            {
                SelectedNode = null;
            }
        }

        [RelayCommand]
        private async Task Submit()
        {
            IsLoading = true;
            try
            {
                var ns = Nodes.ToList();
                var selected = ns.FindAll(q => q.IsParent == true);
                List<int> ids = [];
                if (!OldPPS.IsNullOrEmpty() && selected.IsNullOrEmpty())
                    ids = OldPPS.ConvertAll(q => q.Id);
                if (!OldPPS.IsNullOrEmpty() && !selected.IsNullOrEmpty())
                {
                    foreach (var old in OldPPS)
                    {
                        if (!selected.Any(q => q.Id == old.ProjectID))
                        {
                            ids.Add(old.Id);
                            continue;
                        }
                        selected.First(q => q.Id == old.ProjectID).IsParent = false;
                    }
                }
                var newSelected = selected.FindAll(q => q.IsParent == true);
                if (roleId == 3 && !newSelected.IsNullOrEmpty() && newSelected.Count > 1)
                {
                    GlobalMessage.Instance.ShowWarning("商人只能绑定一个项目！");
                    return;
                }
                List<ProjectPersonAddDto> addList = [];
                foreach (var x in newSelected)
                {
                    addList.Add(new ProjectPersonAddDto() { RoldId = roleId, PersonID = UserId, ProjectID = x.Id });
                }
                if (!ids.IsNullOrEmpty())
                {
                    var resD = await _userService.PPDeleteAsync(ids);
                }
                var res = await _userService.PPBindingAsync(addList);
                DialogHost.CloseDialogCommand.Execute(null, null);
                GlobalMessage.Instance.ShowSuccess("操作成功！");
            }
            catch (Exception rx)
            {
                GlobalMessage.Instance.ShowError(rx.Message);
            }
            finally
            {
                IsLoading = false;
            }
        }

        private async Task LoadData()
        {
            IsLoading = true;
            try
            {
                var res = await _service.GetAllAsync();
                if (res.Data.IsNullOrEmpty())
                    return;
                if (pps.IsNullOrEmpty())
                {
                    var resPP = await _userService.PPGetAllAsync();
                    pps = resPP.Data;
                }
                Nodes.Clear();
                foreach (var data in res.Data)
                {
                    //var pgs = pps.FindAll(q => q.ProjectID == data.Id);
                    //if (!pgs.IsNullOrEmpty() && pgs.Any(q => q.RoldId == roleId&&q.PersonID!= UserId))
                    //{
                    //    continue;
                    //}
                    var p = new TreeNode() { IsParent = false, Id = data.Id, Name = data.Name, Type = 0 };
                    Nodes.Add(p);
                }

                OldPPS = pps.FindAll(q => q.PersonID == UserId);
                if (!OldPPS.IsNullOrEmpty())
                {
                    foreach (var p in OldPPS)
                    {
                        var n = Nodes.FirstOrDefault(q => q.Id == p.ProjectID);
                        if (n == null)
                            continue;
                        n.IsParent = true;
                    }
                }
            }
            catch (Exception rx)
            {
                GlobalMessage.Instance.ShowError(rx.Message);
            }
            finally
            {
                IsLoading = false;
            }
        }
    }
}